package com.badlogic.androidgames;

import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Input.TouchEvent;
import com.badlogic.androidgames.framework.gl.Camera2D;
import com.badlogic.androidgames.framework.gl.SpriteBatcher;
import com.badlogic.androidgames.framework.impl.GLScreen;
import com.badlogic.androidgames.framework.math.OverlapTester;
import com.badlogic.androidgames.framework.math.Rectangle;
import com.badlogic.androidgames.framework.math.Vector2;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

public class EndLevelScreen extends GLScreen {
	Camera2D guiCam;
	SpriteBatcher batcher;
	Rectangle exitBounds;
	Rectangle playBounds;
	Rectangle facebookBounds;
	Vector2 touchPoint;
	final Facebook facebook;
	final SharedPreferences sharedPreferences;
	
	boolean published = false;
	
	public EndLevelScreen(Game game) {
		super(game);

		guiCam = new Camera2D(glGraphics, 480, 800);
		batcher = new SpriteBatcher(glGraphics, 100);
		// soundBounds = new Rectangle(0, 0, 64, 64);
		
		playBounds 		= new Rectangle(50 , 250, 100, 100);
		exitBounds		= new Rectangle(350, 250, 100, 100);
		facebookBounds	= new Rectangle(300, 50 , 100, 100);
		
		touchPoint = new Vector2();

		
		
		facebook = new Facebook("307086602703463");

		sharedPreferences = glGame.getApplicationContext()
				.getSharedPreferences("facebook-credentials",
						Context.MODE_PRIVATE);
		String tok = sharedPreferences.getString("access_token", null);
		facebook.setAccessToken(tok);
		facebook.setAccessExpires(sharedPreferences.getLong("expires_in", 0));
		
		if (!facebook.isSessionValid()) 
		{
			facebookAuth();
		}
		
		Settings.load(game.getFileIO());
	}

	@Override
	public void update(float deltaTime) {
		
		if(glGame.backPressed == true)
		{
			glGame.backPressed = false;
			glGame.finish();
		}
		
		List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
		game.getInput().getKeyEvents();

		int len = touchEvents.size();
		for (int i = 0; i < len; i++) {
			TouchEvent event = touchEvents.get(i);
			touchPoint.set(event.x, event.y);
			guiCam.touchToWorld(touchPoint);

			if (event.type == TouchEvent.TOUCH_UP) {
				if (OverlapTester.pointInRectangle(playBounds, touchPoint)) 
				{
					game.setScreen(new GameScreen(game));
					return;
				}
				if (OverlapTester.pointInRectangle(exitBounds, touchPoint)) 
				{
					game.setScreen(new MainMenuScreen(game));
					return;
				}
				if (OverlapTester.pointInRectangle(facebookBounds, touchPoint) && (published == false)) 
				{	
					final String msg = new String("Ho appena giocato a Great Minds! " +
							"Ho totalizzato il punteggio di " +
							glGame.gameUserData.points);
					postWall(msg);
							
					published = true;
					return;
				}
			}
		}
	}

	
	void facebookAuth()
	{
		glGame.runOnUiThread(new Runnable() 
		{
			public void run() 
			{
				facebook.authorize(glGame, 
						new String[] { "email", "publish_checkins", 
						"publish_actions", "read_stream"},
						Facebook.FORCE_DIALOG_AUTH, new DialogListener() {
					@Override
					public void onComplete(Bundle values) 
					{
						SharedPreferences.Editor editor = sharedPreferences.edit();
						String tt = facebook.getAccessToken();
						editor.putString("access_token", tt);
						editor.putLong("access_expires", facebook.getAccessExpires());
						editor.commit();
					}

					@Override
					public void onFacebookError(FacebookError error) 
					{
					}

					@Override
					public void onError(DialogError e) 
					{
					}

					@Override
					public void onCancel() 
					{
					}
				});
			}
		});
	}
	
	
	public void postWall( final String score)
	{		 
		Thread t = new Thread(new Runnable() {
			public void run() {
				try {
					String response = facebook.request("me");
					Bundle parameters = new Bundle();
					parameters.putString("message", score);
					parameters.putString("description", score);
					response = facebook.request("me/feed", parameters, 
							"POST");
					Log.d("Tests", "got response: " + response);
					if (response == null || response.equals("") || 
							response.equals("false")) {
						Log.v("Error", "Blank response");
					}
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
		});
		t.start();
	}
	
	
	@Override
	public void present(float deltaTime) 
	{
		GL10 gl = glGraphics.getGL();
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		guiCam.setViewportAndMatrices();

		gl.glEnable(GL10.GL_TEXTURE_2D);

		if(published == false)
		{
			batcher.beginBatch(Assets.levelCompletedBGTexture);
				batcher.drawSprite(240, 400, 480, 800, Assets.levelCompletedBG);
			batcher.endBatch();
		}
		else
		{
			batcher.beginBatch(Assets.levelCompletedBGTexture_2);
				batcher.drawSprite(240, 400, 480, 800, Assets.levelCompletedBG_2);
			batcher.endBatch();
		}

		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
				
		gl.glDisable(GL10.GL_BLEND);
	}

	@Override
	public void pause() 
	{
		Settings.save(game.getFileIO());
	}

	@Override
	public void resume() 
	{
	}

	@Override
	public void dispose() 
	{
	}
}